from django.shortcuts import render_to_response, HttpResponseRedirect
from django.template import RequestContext
from django.http import Http404
from django.contrib.auth.views import password_change as auth_password_change
from django.contrib import messages

from models import *
from options import Options
from apps.course.models import Course
from apps.course.functions import course_reverse
from apps.additions.models import GetAdditions, GetAdditionForms
from filetransfers.api import prepare_upload
from apps.files.views.files import post_file, check_permissions
import apps.files as files
from django.contrib.contenttypes.models import ContentType
from PIL import Image

import StringIO
import logging

logger = logging.getLogger('pet.apps.participants.views')

# Create your views here.

def index(request, course=None):
	TheCourse = Course.find_or_404(course)
	TheUser = request.user
	TheCourseParticipant = CourseParticipant.find(course=TheCourse,user=TheUser)
	if not TheCourse.show_class_roster:
		raise Http404
	if not TheCourseParticipant and not request.user.is_superuser:
		messages.info(request,"Access to this part of the site requires course authentication");
		return HttpResponseRedirect(course_reverse('course_index',TheCourse))
	
	Users = CourseParticipant.find(course=TheCourse)
	print "\n\nUsers %s" % Users
	
	return render_to_response('participants/index.html',{'Users':Users},context_instance=RequestContext(request))

def password_change(request, post_change_redirect=None, course=None):
	return auth_password_change(request, post_change_redirect=post_change_redirect)

def view_profile(request, course=None, username=None):
	logger.info("view_profile: course %s, username %s",course,username)
	TheCourse = Course.find_or_404(course)
	
	#Get info for user accessing this page
	TheUser = request.user
	if not TheUser.is_authenticated():
		messages.info(request,'Only authorized and authenticated users have access to this area of the site')
		return HttpResponseRedirect(course_reverse('course_index',TheCourse))
	TargetUser = TheUser
	TheCourseParticipant = None
	#If looking at someone else's profile, you must be registered under that course (and so must they)
	if username and TheCourse:
		TargetUser = User.find_or_404(username)
		TargetCourseParticipant = CourseParticipant.find_or_404(course=TheCourse,user=TargetUser);
		TheCourseParticipant = CourseParticipant.find_or_404(course=TheCourse,user=TheUser)
	
	Additions = GetAdditions(model="User",course=TheCourse.course_id,instanceid=TargetUser)
	return render_to_response('participants/view_profile.html',{'User':TargetUser,
						'Viewer':TheCourseParticipant,'Additions':Additions},context_instance=RequestContext(request))
	
def edit_profile(request, course=None):
	logger.fxn_entry("course=%s",course)

	TheCourse = Course.find_or_404(course)
	
	TheUser = request.user
	TheCourseParticipant = CourseParticipant.find(user=TheUser,course=TheCourse,keep_queryset=True)
	if (not TheUser.is_authenticated()):
		messages.info(request,"Access to this part of the site requires authentication");
		return HttpResponseRedirect(course_reverse('course_index',TheCourse))
	
	#Create forms
	if request.method == "POST":
		InfoForm = UserForm(request.POST,request.FILES,instance=TheUser)
		Additions = GetAdditionForms("User",TheUser,course,request.POST)
	else:
		InfoForm = UserForm(instance=TheUser)
		Additions = GetAdditionForms("User",TheUser,course)
	
	#Check permissions
	if not TheCourse.allow_student_name_and_email_change:
		InfoForm = None
	
	#Process forms
	if request.method == "POST":
		#Make sure user in form is this user!!!!!
		model, target, error = files.get_content_object(request.POST.copy())
		if target and target is not request.user:
			logger.http404("User %s trying to save file as user %s" % (request.user,target))
			raise Http404
		
		HasError = False
		if InfoForm and InfoForm.is_valid() and InfoForm.has_changed():
			InfoForm.save()
			
		if InfoForm and not InfoForm.is_valid(): HasError = True
		
		#if Additions:
		#    for item,form in Additions:
		#        if form.is_valid() and form.has_changed():
		#            form.instance.model = "Participant"
		#            form.instance.instanceid = TargetUser
		#            form.instance.name = item.name
		#            form.save()
		#        elif not form.is_valid(): HasError = True
		
		if 'file' in request.FILES:
			logger.info("Avatar upload by student")
			#Write the file to temp storage
			file = request.FILES['file']
			Pass, Reason = check_permissions(request,using=None,course=TheCourse.course_id)
			if not Pass:
				return Reason
			
			from django.core.files import temp as tempfile
			temp = tempfile.NamedTemporaryFile(suffix=".tmp")
			for chunk in file.chunks():
				temp.write(chunk)
			temp.seek(0)
			
			#Open in PIL and check if it meets avatar reqs
			image = Image.open(temp)
			width,height = image.size
			max_height = Options.get_option("Max Avatar Height",200.0)
			max_width = Options.get_option("Max Avatar Width", 300.0)
			
			#If not, shrink it and save it back to request.FILES
			if (height > max_height or width > max_width):
				aspect_ratio = float(width)/float(height)
				if (max_height/height > max_width/width):
					new_height = max_width/aspect_ratio
					new_width = max_width
				else:
					new_width = max_height*aspect_ratio
					new_height = max_height
					
				image.thumbnail((int(new_width),int(new_height)),Image.ANTIALIAS)
				new_width,new_height=image.size
				from django.core.files.uploadhandler import TemporaryUploadedFile
				request.FILES['file'] = TemporaryUploadedFile(name="avatar.png", content_type=file.content_type, charset=file.charset, size=new_width*new_height*4)
				image.save(request.FILES['file'].file,format='PNG')
			request.FILES['file'].name = "avatar.png"
			
			#Delete temp file
			temp.close()
			
			#Save file
			logger.info("Saving uploaded file via post_file for student")
			FileResponse = post_file(request)
			if (FileResponse.status_code != 302): return FileResponse
					
					
		if not HasError and 'Save' in request.POST and request.POST['Save'] == 'SaveReturn':
			return HttpResponseRedirect(course_reverse('apps.participants.views.view_profile',course,username=TheUser.username))
			
	return render_to_response('participants/edit_profile.html',{'user':TheUser, 'user_form':InfoForm, 'Additions':Additions},
						context_instance=RequestContext(request))
